<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../css/Buttons.css" type="text/css" rel="stylesheet"/>
    <link href="../css/project.css" type="text/css" rel="stylesheet"/>
    <style>
        body {
            background: gray;
        }
        #chatBox {
            text-align: right;
            margin: 0 auto;
            width: 800px;
        }
        #contactBox {
            width: 200px;
            float: left;
        }
        #msgBox {
            margin-left: 230px;
            position: relative;
        }
        .contactBox-Item {
            position: relative;
            width: 100%;
            text-align: center;
            height: 40px;
            line-height: 40px;
            font-size: 20px;
            cursor: pointer;
            margin-bottom: 10px;
            background: whitesmoke;
            border: 3px solid black;
            border-radius: 5px;
        }
        .sign-new-msg {
            background: red;
            position: absolute;
            right: 5px;
            top: 5px;
            height: 10px;
            width: 10px;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<div id="chatBox" class="clearfix">
    <button class="button button-primary button-small" style="margin: 10px;" id="getCustomerBtn">Get Customer</button>
    <button class="button button-primary button-small" style="margin: 10px;" id="logoutBtn">Log Out</button><br/>
    <div id="contactBox"></div>
    <div id="msgBox">

    </div>
    <div id="customServiceBox"></div>
    <div class="waiting">Waiting for Custom Service...</div>
</div>
<script src="../js/jquery-3.2.1.min.js"></script>
<script>
    $(document).ready(function () {
        $.get("/chat/cs/loggedIn", function (result) {
            if (result.status) {
                console.log(result.data);
                customServiceJSON = result.data;
                customServiceChat = new CustomServiceChat(customServiceJSON, "#chatBox");
            }
            else {
                window.location.href = "/cs/cslogin";
            }
        });
    });
    let customServiceJSON;
    let customServiceChat;
    class CustomServiceChat {
        constructor(customServiceJSON, targetDivId) {
            this.state = {
                csPushCustomService: 0,
                csGetMsg: 2
            };
            this.msgState = {
                msg: 1
            };
            this.currentState = this.state.csPushCustomService;
            this.customServiceJSON = customServiceJSON;
            this.loadingUrl = "chrome-extension://hlppekcioiicbfafmmgikkdkljnjpiao/images/loading.gif";
            this.csPushCustomServicetUrl = "/chat/csPushCustomService";
            this.csGetMsgUrl = "/chat/csGetMsg";
            this.csGetCustomerUrl = "/chat/csGetCustomer";
            this.csSendMsgUrl = "/chat/csSendMsg";
            this.csEndChatUrl = "/chat/csEndChat";
            this.msgBox = $("#msgBox");
            this.contactBox = $("#contactBox")
            this.customerArray = [];
            this.getCustomerBtn = $("#getCustomerBtn");
            this.getCustomerBtn.click(function () {
                this.csGetCustomer();
            }.bind(this));
            this.logoutBtn = $("#logoutBtn");
            this.logoutBtn.click(function () {
                $.get("/cs/logout", function (result) {
                    if (result.status) {
                        window.location.href = "/cs/cslogin";
                    }
                    else {
                        alert(result.msg);
                    }
                });
            }.bind(this));
            this.autoScroll = true;

            this.clientChatDiv = $(targetDivId);
            this.ajaxController(this.currentState);
            console.log(this.state);
            this.chattingWithSession = null;
        }

        dealCustomerJSON(customerJSON) {
            customerJSON.chattingEle = $(`<div class='chatting-Head'>` +
                `<div class='chatting-Head-Setting'>` +
                `<div class='chatting-Head-Setting-Inner'>END</div>` +
                `</div>` +
                `<div class='chatting-Head-Quit' onclick=''>` +
                `<div class='chatting-Head-Quit-InnerA'></div>` +
                `<div class='chatting-Head-Quit-InnerB'></div>` +
                `</div>` +
                `<div class='chatting-Head-Title'>${customerJSON.user_name}</div>` +
                `</div>` +
                `<div class='chatting-Body'>` +
                `<div class='chatting-Body-TextArea'></div>` +
                `</div>` +
                `<div class='chatting-Footer'>` +
                `<div class='chatting-Footer-Upload'>` +
                `<span class='button-dropdown button-dropdown-inverse' data-buttons='dropdown'>` +
                `<button style='color: black;' class='button button-borderless button-icon-txt-large'>+</button>` +
                `<ul style='width: 100px' class='button-dropdown-list is-below'>` +
                `<li><a href='#' onclick='$(this).next().click(); return false;'>Send Picture</a>` +
                `<input type='file' accept='image/x-png,image/gif,image/jpeg,image/bmp' id='uploadPicture'` +
                ` style='display: none;' onchange=''/></li>` +
                `<li><a href='#' onclick='$(this).next().click(); return false;'>Send Video</a>` +
                `<input type='file' accept='video/webm' id='uploadVideo' style='display: none;' onchange=''/></li>` +
                `</ul>` +
                `</span>` +
                `</div>` +
                `<div class='chatting-Footer-SendBox'>` +
                `<textarea class='sendBox-TextArea'></textarea>` +
                `</div>` +
                `<button class='button button-glow button-border button-rounded button-primary' id='sendBtn${customerJSON.user_id}'>Send Message</button>` +
                `</div>`);
            customerJSON.chattedEle = $(`<div class="contactBox-Item" id='contactBoxItem${customerJSON.user_id}'>${customerJSON.user_name}
                <div class="sign-new-msg"></div>
            </div>`);
            customerJSON.sign = customerJSON.chattedEle.children(`.sign-new-msg`);
            customerJSON.sign.hide();
            this.customerArray.push(customerJSON);
            this.contactBox.append(customerJSON.chattedEle);
            $(`#contactBoxItem${customerJSON.user_id}`).click(function () {
                this.showChattingEle(customerJSON.user_id);
            }.bind(this));
        }

        showChattingEle(user_id) {
            console.log(user_id);
            let temp = this.getItem(this.customerArray, "user_id", user_id);
            if (temp != null) {
                this.msgBox.html(temp.chattingEle);
                temp.sign.hide();
                this.chattingWithSession = temp.sessionId;
                $(`#sendBtn` + temp.user_id).click(function () {
                    let msg = temp.chattingEle.children('.chatting-Footer-SendBox').children('.sendBox-TextArea').val();
                    if (msg == null || msg === "") {
                        return;
                    }
                    this.pushMsgToMsgDialog(true, msg, temp.chattingEle);
                    this.csSendMsg(temp.sessionId, msg, temp.chattingEle);
                }.bind(this));
                $(`.chatting-Head-Quit`).click(function () {
                    this.closeChattingBox();
                }.bind(this));
                $(`.chatting-Head-Setting-Inner`).click(function () {
                    this.csEndChat(temp.sessionId);
                }.bind(this));
                let textArea = temp.chattingEle.children('.chatting-Body-TextArea');
                textArea.scrollTop(textArea[0].scrollHeight);
                temp.chattingEle.children('.chatting-Footer-SendBox').children('.sendBox-TextArea').focus();
            }
        }

        csSendMsg(sessionId, msg, chattingEle) {
            let customerSessionIdJSON = { customerSessionId: sessionId, msg: msg };
            $.post(this.csSendMsgUrl, customerSessionIdJSON, function (result) {
                if (result.status) {
                    this.csSendMsgSuc(chattingEle);
                }
            }.bind(this));
        }

        csSendMsgSuc(chattingEle) {
            let sendBoxTextArea = chattingEle.children('.chatting-Footer-SendBox').children('.sendBox-TextArea');
            sendBoxTextArea.val("");
            sendBoxTextArea.focus();
        }

        pushMsgToMsgDialog(directionType, msg, targetEle) {
            let msgDialog = targetEle.children(".chatting-Body-TextArea");
            let direction;
            if (directionType) {
                direction = "Right";
            }
            else {
                direction = "Left";
            }
            let textFlag = ``;
            /*if (directionType) {
                //textFlag = `<span class='textArea-Flag'><img src='${this.loadingUrl}' class='textArea-ImgFlag'/></span>`;
            }*/
            let textAreaItemStr = `<div class='textArea-Item clearfix'>` +
                `<div class='textArea-${direction}Item-ProfilePhoto'>` +
                `<img class='img' src='' onerror=''/>` +
                `</div>` +
                `<div class='textArea-${direction}Item-Triangle'></div>` +
                `<div class='textArea-${direction}Item-MsgBox clearfix'>` +
                `<div class='textArea-${direction}Item-MsgDialog clearfix'>${msg}</div>${textFlag}` +
                `</div>` +
                `</div>`;
            msgDialog.append(textAreaItemStr);
            if (this.autoScroll) {
                msgDialog.scrollTop(msgDialog[0].scrollHeight);
            }
        }

        ajaxController() {
            switch (this.currentState) {
                case this.state.csPushCustomService:
                    this.csPushCustomService();
                    break;
                case this.state.csGetMsg:
                    this.csGetMsg();
                    break;
            }
        }

        csPushCustomService() {
            $.get(this.csPushCustomServicetUrl, function (result) {
                if (result.status) {
                    console.log(result);
                    if (result.data != null) {
                        if (result.data instanceof Array) {
                            for (let item of result.data) {
                                this.dealCustomerJSON(item);
                            }
                        }
                    }
                    this.csPushCustomServiceSuc();
                }
                else {
                    this.timeOutToNextAjax();
                }
            }.bind(this));
        }

        csPushCustomServiceSuc() {
            this.currentState = this.state.csGetMsg;
            this.timeOutToNextAjax();
            $(".waiting").hide();
        }

        csGetMsg() {
            $.post(this.csGetMsgUrl, {}, function (result) {
                if (result.status) {
                    this.dealMsgData(result.data);
                }
                this.timeOutToNextAjax();
            }.bind(this));
        }

        csGetCustomer() {
            $.get(this.csGetCustomerUrl, function (result) {
                if (result.status) {
                    let tempJSON = result.data;
                    this.dealCustomerJSON(tempJSON);
                    console.log(result);
                }
                else {
                    console.log(result.msg);
                }
            }.bind(this));
        }

        csEndChat(sessionId) {
            console.log(sessionId);
            $.post(this.csEndChatUrl, { customerSession: sessionId }, function (result) {
                if (result.status) {
                    this.csEndChatSuc(sessionId);
                }
                else {
                    alert(result.msg);
                }
            }.bind(this));
        }

        csEndChatSuc(sessionId) {
            this.removeItem(this.customerArray, "sessionId", sessionId);
            this.updateChatBox();
        }

        updateChatBox() {
            this.contactBox.html("");
            this.msgBox.html("");
            for (let item of this.customerArray) {
                this.contactBox.append(item.chattedEle);
            }
        }

        dealMsgData(msgData) {
            if (Array.isArray(msgData)) {
                if (msgData.length > 0)
                    console.log(msgData);
                for (let i = 0; i < msgData.length; i++) {
                    let item = this.getItem(this.customerArray, "sessionId", msgData[i].sessionId);
                    if (item != null) {
                        switch (msgData[i].stateNumber) {
                            case this.msgState.msg:
                                if (this.chattingWithSession !== item.sessionId) {
                                    item.sign.show();
                                }
                                this.pushMsgToMsgDialog(false, msgData[i].stateMsg, item.chattingEle);
                                break;
                        }
                    }
                }
            }
            else {
                console.log('not array');
            }
        }

        closeChattingBox() {
            this.msgBox.html("");
            this.chattingWithSession = null;
        }

        timeOutToNextAjax() {
            setTimeout(()=>{this.ajaxController()}, 1000);
        }

        removeItem(array, key, value) {
            for (let i = 0; i < array.length; i++) {
                if (array[i][key] === value) {
                    array.splice(i, 1);
                }
            }
        }

        getItem(array, key, value) {
            let flag = null;
            for (let item of array) {
                if (item[key] === value) {
                    flag = item;
                    break;
                }
            }
            return flag;
        }
    }
</script>
</body>
</html>